package com.justech.eat.service.impl;

import com.justech.common.util.DateUtil;
import com.justech.eat.entity.Order;
import com.justech.eat.entity.OrderDetail;
import com.justech.eat.mapper.mysql.OrderDetailMapper;
import com.justech.eat.repository.OrderDetailRepository;
import com.justech.eat.repository.OrderRepository;
import com.justech.eat.service.OrderDetailAbnormalService;
import com.justech.eat.service.OrderDetailService;
import com.justech.eat.service.OrderService;
import com.justech.eat.service.event.OrderDetailAbnormalEvent;
import com.justech.eat.service.event.OrderDetailFinalEvent;
import org.apache.ibatis.jdbc.Null;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Primary
@Service
public class OrderDetailServiceImp implements OrderDetailService, ApplicationListener<OrderDetailAbnormalEvent> {
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    OrderDetailRepository orderDetailRepository;
    @Autowired
    OrderDetailAbnormalService orderDetailAbnormalService;
    @Autowired
    OrderBookSubmit orderBookSubmit;
    @Autowired
    OrderService orderService;
    @Autowired
    OrderRepository orderRepository;

    @Override
    public void add(OrderDetail orderDetail) {
        Date date = new Date();
        orderDetail.setCreateTime(date);
        orderDetailMapper.add(orderDetail);


    }

    @Override
    public void delete(int id) {
        orderDetailMapper.deleteById(id);

    }

    @Override
    public void update(int id, long orderId, int type, int result, boolean isFinal) {
        OrderDetail orderDetail = orderDetailMapper.queryById(id);
        orderDetail.setOrderId(orderId);
        orderDetail.setType(type);
        orderDetail.setResult(result);
        orderDetail.setFinal(isFinal);
        Date date = new Date();
        orderDetail.setUpdateTime(date);
        orderDetailMapper.update(orderDetail);
    }

    @Override
    public OrderDetail queryById(int id) {
        OrderDetail orderDetail = orderDetailMapper.queryById(id);
        return orderDetail;
    }

    /**
     * 受理订单明细更改
     *
     * @param id
     * @param result
     * @return
     */
    @Override
    public OrderDetail update(int id, int result) {
        return null;
    }

    /**
     * 修改对象
     *
     * @param orderDetail
     * @return
     */
    @Override
    public OrderDetail update(OrderDetail orderDetail) {
        if (orderDetail == null) return null;
        orderDetail.setUpdateTime(DateUtil.now());
        return orderDetailRepository.saveAndFlush(orderDetail);
    }

    /**
     * 查询用户订餐记录
     *
     * @param date
     * @param jobNumber
     * @param type
     * @return
     */
    @Override
    public OrderDetail getOrderDetail(String date, String jobNumber, int type) {
        Order repository = orderRepository.findByDateAndJobNumber(date, jobNumber);
        if (repository != null) {
            return orderDetailRepository.findByOrderIdAndType(repository.getId(), type);
        }
        return null;
    }

    /**
     * 处理异常结果
     *
     * @param date
     * @param jobNumber
     * @param type
     * @param result
     * @return
     */
    @Override
    public OrderDetail processAbnormal(String date, String jobNumber, int type, int result) {
        OrderDetail abnromalDetail = null;
        Long orderId = null;
        OrderDetail orderDetail = getOrderDetail(date, jobNumber, type);
        if (orderDetail == null) {
            OrderDetail detail = new OrderDetail();
            detail.setResult(result);
            detail.setType(type);
            Order order = orderBookSubmit.submit(date, jobNumber, detail);
            orderId = order.getId();
            abnromalDetail = getDetailByType(order.getOrderDetails(), type);
        } else {
            orderDetail.setResult(result);
            abnromalDetail = update(orderDetail);
        }
        orderId = (orderId == null) ? abnromalDetail.getOrderId() : orderId;
        try {
            orderDetailAbnormalService.add(orderId, abnromalDetail.getId(), jobNumber, type);
        } catch (NullPointerException e) {
            System.out.println(e);
        }
        return null;
    }


    private OrderDetail getDetailByType(List<OrderDetail> details, int type) {
        for (OrderDetail detail : details) {
            if (detail.getType() == type) {
                return detail;
            }
        }
        return null;
    }


    /**
     * 处理将要订版的记录
     *
     * @param date
     * @param jobNumber
     * @param type
     * @return
     */
    @Override
    public OrderDetail finalOrderDetail(String date, String jobNumber, int type) {
        OrderDetail orderDetail = getOrderDetail(date, jobNumber, type);
        if (orderDetail != null) {
            orderDetail.setResult(1);
            orderDetail.setFinal(true);
            orderDetail.setStatus(2);
            orderDetail.setUpdateBy("Self service settlement system");
            orderDetail.setUpdateTime(DateUtil.now());
            orderDetail = orderDetailRepository.saveAndFlush(orderDetail);
        }
        return orderDetail;
    }

    @Override
    public void onApplicationEvent(OrderDetailAbnormalEvent orderDetailAbnormalEvent) {
        Long orderDetailId = orderDetailAbnormalEvent.getOrderDetail().getId();
        int result = orderDetailAbnormalEvent.getResult();
        Optional<OrderDetail> orderDetail = orderDetailRepository.findById(orderDetailId);
        if (orderDetail.isPresent()) {
            OrderDetail detail = orderDetail.get();
            if (!detail.isFinal()) {
                detail.setStatus(2);
                detail.setResult(result);
                detail = update(detail);
                /*保存异常*/
                orderDetailAbnormalService.add(detail.getOrderId(), detail.getId(), orderDetailAbnormalEvent.getOrder().getJobNumber());
            }
        }

    }
}
